package com.project.controller.managerController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.project.bean.ManagerBean;
import com.project.bean.UserBean;
import com.project.service.managerService.IManagerService;
import com.project.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/manager")
public class ManagerController {
    @Autowired
    private IManagerService managerService;

    @RequestMapping("/login")
    public ManagerBean login(String code, String psw, HttpServletRequest request) throws Exception {
        ManagerBean user = managerService.login(code,psw);
        if (user==null){
            return null;
        }
        if("门店管理员".equals(user.getType())){
            ManagerBean manager = managerService.findById(user.getId());
            if(manager != null){
                request.getSession().setAttribute("loginUser", manager);
                return manager;
            }
        }
        request.getSession().setAttribute("loginUser", user);
        return user;
    }

    @RequestMapping("/getUser")
    public String login( HttpServletRequest request) throws Exception {
        ManagerBean user=(ManagerBean) request.getSession().getAttribute("loginUser");
        if(user!=null){
            ManagerBean loginUser=managerService.findById(user.getId());
            String userStr=new ObjectMapper().writeValueAsString(loginUser);
            return userStr;
        };
        String userStr=new ObjectMapper().writeValueAsString(user);
        return userStr;

    };

    @RequestMapping("/add")
    public String add(ManagerBean manager,@RequestParam("face") MultipartFile mf) throws Exception {
        String fileName = UploadUtil.upload(mf,"static/html/img");
        manager.setFaceImg(fileName);
        managerService.add(manager);
        return "ok";
    }

    @RequestMapping("/findById")
    public ManagerBean findById(int id) {
        return managerService.findById(id);
    }

    @RequestMapping("/findByItem")
    public PageInfo<ManagerBean> findByItem(int pageNO, String code, String state) {
        return managerService.findByItem(pageNO,code, state);
    }

    @RequestMapping("/findAll")
    public PageInfo<ManagerBean> findAll(int pageNO) {
        return managerService.findAll(pageNO);
    }
}
